package promote.brozen.netty.codec.marshalling;

import io.netty.handler.codec.marshalling.*;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;

/**
 * @author Brozen
 * @date 2020/9/29 8:47 AM
 * @email brozen@qq.com
 */
public class MarshallingCodecFactory {

    public static MarshallingDecoder newDecoder() {
        // serial表示Java序列化工厂对象，由jboss-marshalling-serial-xxx.jar提供，没有要先添加依赖
        // 通过SPI加载org.jboss.marshalling.ProviderDescriptor接口的实现，每一种MarshallingFactory会有一个ProviderDescriptor
        MarshallerFactory factory = Marshalling.getProvidedMarshallerFactory("serial");

        // 设置版本号
        MarshallingConfiguration config = new MarshallingConfiguration();
        config.setVersion(5);

        // 创建decoder，1024是单个对象序列化后的最大长度
        DefaultUnmarshallerProvider provider = new DefaultUnmarshallerProvider(factory, config);
        MarshallingDecoder decoder = new MarshallingDecoder(provider, 1024);
        return decoder;
    }

    public static MarshallingEncoder newEncoder() {
        MarshallerFactory factory = Marshalling.getProvidedMarshallerFactory("serial");

        MarshallingConfiguration config = new MarshallingConfiguration();
        config.setVersion(5);

        MarshallerProvider provider = new DefaultMarshallerProvider(factory, config);
        return new MarshallingEncoder(provider);
    }

}
